<!--
 * @Autor: wanghan
 * @Date: 2022-01-07 18:28:36
 * @LastEditors: wanghan
 * @LastEditTime: 2022-02-08 16:43:34
 * @Description: 军标方案
-->
<template>
    <div class="mgs-plotting-plan-view">
        <!-- 军标方案 -->
        <MgsPlottingPlan
            v-loading="loading"
            :bind-map="bindMap"
            :visible-plot-panel="openPlotPanel"
            :load-handle="getPlotPlanData"
            :load-hotspot-handle="getHotspotList"
            :remove-handle="removePlotPlanHandle"
            :save-handle="savePlanHandle"
            :save-hotspot-handle="saveHotspotHandle"
            :remove-hotspot-handle="removeHotspotHandle"
            :clear-feature-status="clearFeatureStatus"
        />
        <!-- 标绘面板 -->
        <MgsDrag
            title="标绘面板"
            :visible.sync="plotPanelVisible"
            style="
                top: 66px;
                right: 75px;
                height: 85vh;
                width: 350px;
                overflow: unset;
            "
        >
            <MgsPlottingPanel
                :bind-map="bindMap"
                :data="PlotDirData"
                :selected-feature="featureSelected"
                :get-plot-list="getPlotDirList"
                :change-style-handle="featuresmodified"
            />
            <!-- 标绘工具 -->
            <MgsPlottingMenu
                v-if="bindMap && bindMap.MapType === '2D'"
                :bind-map="bindMap"
                style="position: absolute; top: 28%; left: -50px"
            ></MgsPlottingMenu>
        </MgsDrag>
    </div>
</template>

<script>
import MgsDrag from '@mgs/components-basic/mgs-drag.vue';
import MgsPlottingPlan from '@mgs/components/mgs-plot/mgs-plotting-plan';
import MgsPlottingPanel from '@mgs/components/mgs-plot/mgs-plotting-panel.vue';
import MgsPlottingMenu from '@mgs/components/mgs-plot/mgs-plotting-menu.vue';

import { transformToTreeData } from '@mgs/utils/tree';
import { createUuid, dateFormat } from '@mgs/utils/misc';
import PlotApi from '@/apis/plotApi';
import API from '@mgs/utils/api';

export default {
    components: { MgsPlottingPlan, MgsPlottingPanel, MgsPlottingMenu, MgsDrag },
    props: {
        bindMap: Object,
    },
    data() {
        return {
            // 加载状态
            loading: false,
            plotPanelVisible: false,
            // 军标标号目录
            PlotDirData: [],
            hotspotData: [],
            // 标号相关
            featureAdd: [], //新标的标号
            featureEdit: [], //修改后的标号  (不是新增的)
            featureSelected: [],
        };
    },
    created() {
        this.getPlotDirData();
    },
    mounted() {
        this.watchBindMapHandle();
    },
    watch: {
        plotPanelVisible(v) {
            const mode = v ? 'edit' : 'select';
            this.bindMap.setPlottingMode(mode);
        },
    },
    methods: {
        watchBindMapHandle() {
            // 监听bindMap获取到值
            this.$watch('bindMap', (newV, oldV) => {
                if (
                    (newV && !oldV) ||
                    (newV && oldV && newV.MapType !== oldV.MapType)
                ) {
                    // 标号被绘制完成 - featureadded
                    this.bindMap.$on('featureadded', evt => {
                        this.featureAdd.push(evt);
                    });
                    // 标号被绘制完成 - featureadded
                    this.bindMap.$on('featuresselected', evt => {
                        this.featureSelected = evt;
                    });
                    // 标号被绘制完成 - featureadded
                    this.bindMap.$on('featuresunselected', () => {
                        this.featureSelected = [];
                    });
                    // 标号被编辑事件 - featuresmodified
                    this.bindMap.$on('featuresmodified', evt => {
                        this.featuresmodified(evt[0]);
                        console.log('被编辑', evt);
                    });
                }
            });
        },
        /**
         * @name 记录标号
         */
        featuresmodified(evt) {
            let flg = false;
            this.featureAdd.map(res => {
                if (
                    (res.uuid && res.uuid === evt.uuid) ||
                    (res.id && res.id === evt.id)
                ) {
                    res = evt;
                    flg = true;
                }
            });
            this.featureEdit.forEach(res => {
                if (
                    (res.uuid && res.uuid === evt.uuid) ||
                    (res.id && res.id === evt.id)
                ) {
                    res = evt;
                    flg = true;
                }
            });
            if (!flg) {
                this.featureEdit.push(evt);
            }
        },
        /**
         * @name 打开标绘面板
         */
        openPlotPanel(flag = true) {
            this.plotPanelVisible = flag;
        },
        /**
         * @name 获取标绘方案数据
         */
        getPlotPlanData(params, callback) {
            this.loading = true;
            PlotApi.getPlotPlanList({
                pageSize: params.pageSize,
                pageNo: params.pageNo,
            })
                .then(res => {
                    callback ? callback(res || null) : '';
                })
                .finally(() => (this.loading = false));
        },
        /**
         * @name 删除方案
         */
        removePlotPlanHandle(param, callback) {
            PlotApi.removePlotPlan(param).then(res => {
                callback ? callback(res || null) : '';
            });
        },
        /**
         * @name 获取标绘目录
         */
        getPlotDirData() {
            PlotApi.getPlotDir().then(res => {
                this.PlotDirData = transformToTreeData(res, {
                    idKey: 'pkid',
                    parentKey: 'parent_id',
                    labelKey: 'symbol_name',
                });
                console.log('获取到plot数据', this.PlotDirData);
            });
        },
        /**
         * @name 获取标绘目录标号
         */
        getPlotDirList(pkid, callback) {
            PlotApi.getPlotDirItem({ parent_id: pkid }).then(res => {
                if (res) {
                    res.forEach(d => {
                        d.src =
                            './img/SymbolIcon' +
                            d.symbol_imgpath.split('SymbolIcon')[1];
                    });
                }
                callback ? callback(res || null) : '';
            });
        },
        /**
         * @name 获取方案热点数据
         */
        getHotspotList(obj, callback) {
            PlotApi.getPlotPlanHotpot({ topic_id: obj.pkid }).then(res => {
                this.hotspotData = res || [];
                callback ? callback(res || null) : '';
            });
        },
        /**
         * @name 方案保存
         */
        savePlanHandle(obj, callback) {
            const planId = obj.id ? obj.id : createUuid();
            let Fun = PlotApi.addPlotPlan;
            if (obj.id) {
                Fun = PlotApi.updatePlotPlan;
            }
            Fun({
                pkid: planId,
                topic_name: obj.name, //	专题名称
                create_time: dateFormat('YYYY-mm-dd HH:MM:SS', new Date()), //	创建时间
                update_time: dateFormat('YYYY-mm-dd HH:MM:SS', new Date()), //	更新时间
            }).then(() => {
                this.$message.success('保存成功');
                callback ? callback(planId) : '';
            });
        },
        /**
         * @name 保存方案的热点
         */
        saveHotspotHandle(planId, callback) {
            const params = [];
            this.featureAdd.forEach(item => {
                const options = this.bindMap.plottingObj2Json(item);

                const param = {
                    pkid: createUuid(),
                    topic_id: planId, //专题id
                    hotpot_name: item.symbolName, //热点名称
                    plot_name: item.symbolName, //标号名称
                    plot_libid: item.libID, //标号id
                    plot_code: item.code, //
                    plot_latlngs: JSON.stringify(
                        item.latLngs || item.localPoints
                    ).toString(), //坐标
                    plot_options: options, //自定义参数
                    plot_customcode: item.code, //自定义编号
                    plot_symboltype: item.symbolType, //标号类型
                    img_base64: '', //自定义图片标号的base64编码
                    create_time: dateFormat('YYYY-mm-dd HH:MM:SS', new Date()),
                };
                const data = PlotApi.savePlotPlanHotpot.process(param);
                params.push(data);
                //前端做keyworld拆分
            });

            // 更新
            this.featureEdit.forEach(item => {
                let pkid = null;
                this.hotspotData.map(res => {
                    const plot_options = JSON.parse(res.plot_options);
                    const uuid = item.uuid || item.id;
                    const plotUuid = plot_options.uuid || plot_options.id;
                    if (uuid === plotUuid) {
                        pkid = res.pkid;
                    }
                });
                if (pkid) {
                    const options = this.bindMap.plottingObj2Json(item);

                    const param = {
                        pkid: pkid,
                        topic_id: planId, //专题id
                        hotpot_name: item.symbolName, //热点名称
                        plot_name: item.symbolName, //标号名称
                        plot_libid: item.libID, //标号id
                        plot_code: item.code, //
                        plot_latlngs: JSON.stringify(
                            item.latLngs || item.localPoints
                        ).toString(), //坐标
                        plot_options: options, //自定义参数
                        plot_customcode: item.code, //自定义编号
                        plot_symboltype: item.symbolType, //标号类型
                        img_base64: '', //自定义图片标号的base64编码
                        create_time: dateFormat(
                            'YYYY-mm-dd HH:MM:SS',
                            new Date()
                        ),
                    };
                    const data = PlotApi.updatePlotPlanHotpot.process(param);
                    params.push(data);
                }
                //前端做keyworld拆分
            });
            API.processBatch(params).then(() => {
                console.log('打印编辑style', this.featureEdit, params);
                this.clearFeatureStatus();
                callback ? callback() : '';
            });
        },
        clearFeatureStatus() {
            this.featureAdd = [];
            this.featureEdit = [];
        },
        removeHotspotHandle(param, callback) {
            PlotApi.removePlotPlanHotpot(param).then(res => {
                callback ? callback(res || null) : '';
            });
        },
    },
};
</script>
